import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

import login from '@/views/login'
import layout from '@/views/layout'
import home from '@/views/home'
import ask from '@/views/ask'
import video from '@/views/video'
import mine from '@/views/mine'
import store from '../store'
import edit from '@/views/mine/edit'
import chat from '@/views/mine/chat'
import article from '@/views/article'
import Search from '@/views/home/Search'
import result from '@/views/home/result'

const routes = [
 {path:'',redirect:'/layout/home'},
 {name:'login',path:'/login',component:login},
 {name:'article',path:'/article',component:article},
 {name:'Search',path:'/Search',component:Search},
 {name:'result',path:'/result',component:result},
 {name:'edit',path:'/mine/edit',component:edit,meta:{needLogin:true}},
 {name:'chat',path:'/mine/chat',component:chat,meta:{needLogin:true}},
 {name:'layout',
 path:'/layout',
 component:layout,
 children:[
  {name:'home',path:'home',component:home,meta:{needLogin:true}},
  {name:'ask',path:'ask',component:ask},
  {name:'video',path:'video',component:video},
  {name:'mine',path:'mine',component:mine ,meta:{needLogin:true}}
 ]
}
]

const router = new VueRouter({
  routes
})

router.beforeEach((to,from,next)=>{
  if(to.meta.needLogin){
    if(store.state.tokenObj.token){
      next()
    }else{
      Vue.prototype.$toast.fail('请先登录')
      next({
        name:'login',
        query:{
          back:to.path
        }
      })
    }
  }else{
    next()
  }
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

export default router
